package org.jflame.auth.web.filter;

import org.jflame.auth.LoginUser;
import org.jflame.auth.authc.AuthcException;
import org.jflame.auth.context.UserContextHolder;
import org.jflame.auth.session.SessionInfo;
import org.jflame.auth.session.SessionRegistry;
import org.jflame.auth.web.CompositeLogoutHandler;
import org.jflame.auth.web.DefaultLogoutHandler;
import org.jflame.auth.web.LogoutHandler;
import org.jflame.commons.model.CallResult;
import org.jflame.commons.model.CallResult.ResultEnum;
import org.jflame.commons.util.StringHelper;
import org.jflame.web.RedirectStrategy;
import org.jflame.web.filter.IgnoreUrlMatchFilter;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends IgnoreUrlMatchFilter {

    private SessionRegistry sessionRegistry;
    private RedirectStrategy kickOutRedirect;
    private RedirectStrategy loginRedirect;
    private LogoutHandler handlers;
    private boolean enableKickOut;

    public LoginFilter() {
    }

    public LoginFilter(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
        handlers = new CompositeLogoutHandler(new DefaultLogoutHandler());
        enableKickOut = true;
    }

    @Override
    protected void doInternalInit(FilterConfig filterConfig) {
        String loginUrl = filterConfig.getInitParameter("loginUrl");
        if (StringHelper.isEmpty(loginUrl)) {
            loginUrl = "/login";
        }
        String kickOutUrl = filterConfig.getInitParameter("kickOutUrl");
        if (StringHelper.isEmpty(kickOutUrl)) {
            kickOutUrl = loginUrl;
        }
        loginRedirect = new RedirectStrategy(loginUrl, new CallResult<>(ResultEnum.NO_AUTH.getStatus(), "会话已过期,请重新登录"));
        kickOutRedirect = new RedirectStrategy(kickOutUrl,
                new CallResult<>(ResultEnum.NO_AUTH.getStatus(), "此会话已过期，可能是由于使用同一用户尝试多个并发登录"));
    }

    @Override
    protected void doInternalFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        Optional<LoginUser> userOpl = UserContextHolder.getLoginUser();
        if (userOpl.isPresent()) {
            // 并发踢人处理
            if (enableKickOut) {
                SessionInfo info = this.sessionRegistry.getSessionInfo(request.getSession(false)
                        .getId());
                if (info != null) {
                    if (info.isExpired()) {
                        handlers.logout(request, response, userOpl.get());
                        kickOutRedirect.redirect(request, response);
                        return;
                    }
                    this.sessionRegistry.refreshLastRequest(info.getSessionId());
                }
            }
        } else {
            loginRedirect.redirect(request, response);
            return;
        }

        chain.doFilter(request, response);
    }

    protected void authenticate(HttpServletRequest request) throws AuthcException {

    }

    public void setLogoutHandlers(LogoutHandler[] handlers) {
        this.handlers = new CompositeLogoutHandler(handlers);
    }

    public void setLogoutHandlers(List<LogoutHandler> handlers) {
        this.handlers = new CompositeLogoutHandler(handlers);
    }

    public void setEnableKickOut(boolean enableKickOut) {
        this.enableKickOut = enableKickOut;
    }

}
